package com.qf.fmall2302.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2302.user.entity.Users;
import com.qf.fmall2302.user.mapper.UsersMapper;
import com.qf.fmall2302.user.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2302.utils.FmallConstants;
import com.qf.fmall2302.vo.UserRegistVo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.RandomUtil;

import java.util.Date;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2023-08-22
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void regist(UserRegistVo userRegistVo) throws Exception {
        String username = userRegistVo.getUsername();
        //1. 比对传入的两个密码是否一致
        String p1 = userRegistVo.getPassword();
        String p2 = userRegistVo.getRepassword();
        if (!p1.equals(p2)){
            throw new Exception("用户输入的密码不一致");
        }

        //2. 判断用户名是否重复
        Users dbuser = this.getOne(new QueryWrapper<Users>().eq("username", username));
        if (dbuser!=null){
            throw new Exception("用户名重复了");
        }

        //3. 生成随机盐
        String salt = RandomUtil.randomString(8);

        //4. 生成md5密码
        String md5password = new Md5Hash(p1, salt, FmallConstants.HASH_TIMES).toHex();

        //5. 补充一些数据库表中的必传字段
        Users newUser = new Users();
        newUser.setUsername(username);
        newUser.setPassword(md5password);
        newUser.setSalt(salt);
        newUser.setUserRegtime(new Date());
        newUser.setUserModtime(new Date());

        //6. 落库
        this.save(newUser);

    }
}
